﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Services;
using Microsoft.Reporting.WinForms;
using MarginTrading.Common;
using System.IO;
using System.Threading;

namespace MarginTrading.Forms
{
    public partial class MarginTradingStatus : Form
    {
        private delegate void DoWorkDelegate(int delay);
        private delegate void ReportOnProgressDelegate(int progress,
                                               string msg);
        string reportSaveLocation = string.Empty;
        string AgentCode = "ctc";

        public MarginTradingStatus()
        {
            InitializeComponent();
        }

        private void LoadReport(string advisorId)
        {
            try
            {
                

                Advisor advisor = AdvisorServices.GetAdvisorByCode(advisorId);

                if (advisor == null)
                {
                    //advisor = AdvisorServices.GetAdvisorByCode(advisorId.ToUpper());
                    //if (advisor == null)
                    //{
                    advisor = new Advisor();
                    advisor.Code = "All";
                    //}
                    //else
                    //{
                    //    advisorId = advisorId.ToUpper();
                    //}
                }
                ReportDataSource ds = new ReportDataSource();
                ds.Name = "master";

                if (advisorId != "All")
                {
                    ds.Value = ReportServices.GetMarginTradingStatusByAdvisor(advisorId, AgentCode);
                }
                else
                {
                    ds.Value = ReportServices.GetMarginTradingStatusByAdvisor(AgentCode);
                }


                this.reportViewer1.LocalReport.ReportPath = "MarginTradingStatus.rdlc";
                this.reportViewer1.LocalReport.DataSources.Clear();
                this.reportViewer1.LocalReport.DataSources.Add(ds);



                //TODO:Remove this 
                string strAgentCode = Reports.AGENT_CODE;

                this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] {
                        new ReportParameter("ImageLink",strAgentCode.ToLower()),
                        new ReportParameter("CompanyName",Reports.COMPANY_NAME),
                        new ReportParameter("AdvisorID",advisor.Code),
                        new ReportParameter("AdvisorName",string.Concat(advisor.Initials, 
                                                            " ",advisor.Name, 
                                                            " ", advisor.Surname) ),
                        new ReportParameter("ReportTitle",Reports.MARGIN_TRADING_TITLE)});

                this.reportViewer1.RefreshReport();
                reportViewer1.SetDisplayMode(DisplayMode.PrintLayout);
                reportViewer1.ZoomMode = ZoomMode.Percent;
                reportViewer1.ZoomPercent = 100;
            }
            catch (Exception e)
            {
                ErrorLog.WriteToEventLog(e.Message);
            }
        }

        private void LoadReport(string advisorId, string agentCode)
        {
            try
            {
                Advisor advisor = AdvisorServices.GetAdvisorByCode(advisorId);

                if (advisor == null)
                {
                    advisor = new Advisor();
                    advisor.Code = "All";
                }
                ReportDataSource ds = new ReportDataSource();
                ds.Name = "master";

                if (advisorId != "All")
                {
                    ds.Value = ReportServices.GetMarginTradingStatusByAdvisorAndAgent(advisorId, agentCode);
                }
                else
                {
                    ds.Value = ReportServices.GetMarginTradingStatusByAdvisorAndAgent(agentCode);
                }


                this.reportViewer1.LocalReport.ReportPath = "MarginTradingStatus.rdlc";
                this.reportViewer1.LocalReport.DataSources.Clear();
                this.reportViewer1.LocalReport.DataSources.Add(ds);



                //TODO:Remove this 
                string strAgentCode = Reports.AGENT_CODE;

                this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] {
                        new ReportParameter("ImageLink",strAgentCode.ToLower()),
                        new ReportParameter("CompanyName",Reports.COMPANY_NAME),
                        new ReportParameter("AdvisorID",advisor.Code),
                        new ReportParameter("AdvisorName",string.Concat(advisor.Initials, 
                                                            " ",advisor.Name, 
                                                            " ", advisor.Surname) ),
                        new ReportParameter("ReportTitle",Reports.MARGIN_TRADING_TITLE)});

                this.reportViewer1.RefreshReport();
                reportViewer1.SetDisplayMode(DisplayMode.PrintLayout);
                reportViewer1.ZoomMode = ZoomMode.Percent;
                reportViewer1.ZoomPercent = 100;
            }
            catch (Exception e)
            {
                ErrorLog.WriteToEventLog(e.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;

            if (AgentCode.ToLower() != "ctc")
            {
                if (!String.IsNullOrEmpty(ddlAdvisor.Text))
                {
                    LoadReport(ddlAdvisor.Text);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(ddlAdvisor.Text) && !String.IsNullOrEmpty(ddlAgent.Text))
                {
                    if (ddlAgent.Text.ToLower() == "ctc")
                    {
                        LoadReport(ddlAdvisor.Text);
                    }
                    else
                    {
                        LoadReport(ddlAdvisor.Text, ddlAgent.Text);
                    }
                }
            }

            button1.Enabled = true;
        }

        private void lblClientID_Click(object sender, EventArgs e)
        {

        }

        private void MarginTradingStatus_Load(object sender, EventArgs e)
        {
            Config AgentCodeConfig = ConfigServices.GetConfigByName("Agent Code");
            if (AgentCodeConfig != null)
            {
                AgentCode = AgentCodeConfig.Value;
            }

            DataTable advisor = AdvisorServices.GetAdvisorCollectionDataTable();
            DataRow dr = advisor.NewRow();
            dr["CODE"] = "All";
            advisor.Rows.InsertAt(dr, 0);
            ddlAdvisor.DisplayMember = "CODE";
            ddlAdvisor.ValueMember = "CODE";
            ddlAdvisor.DataSource = advisor;

            if (AgentCode.ToLower() == "ctc")
            {
                DataTable agent = AgentServices.GetAgentCollectionDataTable();
                ddlAgent.DisplayMember = "CODE";
                ddlAgent.ValueMember = "CODE";
                ddlAgent.DataSource = agent;
                
            }
            else
            {
                ddlAgent.Visible = false;
                label1.Visible = false;
            }

            rbtPDF.Checked = true;
        }

        private void btnExportAll_Click(object sender, EventArgs e)
        {
            try
            {
                // Disable the button
                btnExportAll.Enabled = false;
                folderBrowserDialog1.SelectedPath = "";
                folderBrowserDialog1.ShowDialog();

                if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                {
                    reportSaveLocation = folderBrowserDialog1.SelectedPath;

                    // Create delegate and make async call
                    DoWorkDelegate worker =
                      new DoWorkDelegate(DoWork);
                    worker.BeginInvoke(
                      100,
                      new AsyncCallback(DoWorkComplete),
                      worker);
                }
                else
                {
                    btnExportAll.Enabled = true;
                }
            }
            catch (Exception)
            {
            }
        }

        private void DoWork2(int delay)
        {
            for (int progress = 0; progress < 100; progress += 1)
            {
                Thread.Sleep(delay);
                ReportOnProgress(progress, string.Format("{0}% done", progress));
            }
        }

        private void ReportOnProgress(int progress, string msg)
        {
            if (progressBar1.InvokeRequired)
            {
                progressBar1.Invoke(new ReportOnProgressDelegate(ReportOnProgress),
                  new object[] { progress, msg });
            }
            else
            {
                progressBar1.Value = progress;
                lblProgress.Text = msg;
            }
        }

        private void DoWorkComplete(IAsyncResult workID)
        {
            EnableStartButton();
            DoWorkDelegate worker = workID.AsyncState as DoWorkDelegate;
            worker.EndInvoke(workID);
            ReportOnProgress(100, "100% Completed");
            Thread.Sleep(1000);
            ReportOnProgress(0, "");
        }

        private void EnableStartButton()
        {
            if (btnExportAll.InvokeRequired)
            {
                btnExportAll.Invoke(new MethodInvoker(EnableStartButton));
            }
            else
            {
                btnExportAll.Enabled = true;
            }
        }

        private void DoWork(int delay)
        {
            Config AgentCodeConfig = ConfigServices.GetConfigByName("Agent Code");
            string AgentCode = "cts";
            if (AgentCodeConfig != null)
            {
                AgentCode = AgentCodeConfig.Value;
            }

            LocalReport localReport = new LocalReport();
            localReport.ReportPath = "MarginTradingStatus.rdlc";

            AdvisorCollection advisorCollection = AdvisorServices.GetAdvisorCollection();

            int index = 0;

            //float a = (index / advisorCollection.Count);
            int progress = 0;


            //TODO:Remove this 
            AgentCode = Reports.AGENT_CODE;

            if (rbtPDF.Checked)
            {
                foreach (Advisor advisor in advisorCollection)
                {
                    index++;
                    progress = (index * 100) / advisorCollection.Count;
                    ReportOnProgress(progress, string.Format("{0}% Completed", progress));

                    ReportDataSource ds = new ReportDataSource();
                    ds.Name = "master";
                    ds.Value = ReportServices.GetMarginTradingStatusByAdvisor(advisor.Code, AgentCodeConfig.Value);
                    localReport.EnableExternalImages = true;

                    localReport.DataSources.Clear();
                    localReport.DataSources.Add(ds);

                    localReport.SetParameters(new ReportParameter[] {
                        new ReportParameter("ImageLink", AgentCode.ToLower()),
                        new ReportParameter("CompanyName", Reports.COMPANY_NAME),
                        new ReportParameter("AdvisorID", advisor.Code),
                        new ReportParameter("AdvisorName",string.Concat(advisor.Initials, 
                                                            " ",advisor.Name, 
                                                            " ", advisor.Surname) ),
                        new ReportParameter("ReportTitle",Reports.MARGIN_TRADING_TITLE)});

                    Warning[] warnings;
                    string[] streamIds;
                    string mimeType = string.Empty;
                    string encoding = string.Empty;
                    string extension = string.Empty;
                    byte[] bytes = localReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
                    String strfilename = System.IO.Path.GetRandomFileName();
                    using (FileStream fs = new FileStream(reportSaveLocation + @"\" + advisor.Code + ".pdf", FileMode.Create))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }

                    Thread.Sleep(delay);
                }
            }
            else
            {
                DataTable dt = ReportServices.GetMarginTradingStatus(AgentCodeConfig.Value);
                StreamWriter sw = new StreamWriter(reportSaveLocation + @"\" + "MTStatus.csv", false);

                int iColCount = dt.Columns.Count;

                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(dt.Columns[i]);
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write(dr[i].ToString());
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(",");
                        }

                    }
                    sw.Write(sw.NewLine);

                    index++;
                    progress = (index * 100) / dt.Rows.Count;
                    ReportOnProgress(progress, string.Format("{0}% Completed", progress));

                    Thread.Sleep(delay);
                }
                sw.Close();
            }
        }

        private void DataTableToCSV(DataTable dt, string filePath)
        {
            StreamWriter sw = new StreamWriter(filePath, false);

            int iColCount = dt.Columns.Count;

            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());
                    }
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }

                }
                sw.Write(sw.NewLine);
            }
            sw.Close();
        }
    }
}
